import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { getMyPubLish, takeOffShelves, deleteDemand } from '@/business/services/user/userInfo';

/**
 * @description 我发布的需求列表
 * @author Shawn
 */

type RequestFunction = (pageParams: PageParams, type: string, isAppend?: boolean) => Promise<void>;

type State = {
  // 我发布的需求列表
  myPublishList: any[];
  // 获取到的分页信息
  pageInfo: PageInfo;
  // 数据是否加载完成
  isDataLoaded: boolean;
  // 是否有更多数据
  hasMore: boolean;
};

type Actions = {
  // 获取我发布的需求列表
  getMyPublishList: RequestFunction;
  // 上拉加载
  handlePullUpOrDown: RequestFunction;
  // 上架/下架需求
  handleReOperate: (demandId: string, type: string) => Promise<void>;
  // 删除需求
  handleDelete: (demandId: string) => Promise<void>;
};

const initialState: State = {
  // 我发布的需求列表
  myPublishList: [],
  // 获取到的分页信息
  pageInfo: {},
  // 数据是否加载完成
  isDataLoaded: true,
  // 是否有更多数据
  hasMore: true,
};

export const myPublishStore = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取我发布的需求列表
     * @param pageParams 分页
     * @param isAppend 是否追加数据（用于上拉加载）
     */
    getMyPublishList: async (pageParams: PageParams, type: string, isAppend = false) => {
      set((state) => {
        state.isDataLoaded = true;
      });
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const requestData = {
          ...pageParams,
          type,
        };
        const result = await getMyPubLish(requestData);
        if (result.success) {
          set((state) => {
            if (isAppend) {
              state.myPublishList = [...state.myPublishList, ...result?.data];
            } else {
              state.myPublishList = result?.data;
            }
            state.pageInfo = {
              pageIndex: result?.current,
              pageSize: result?.pageSize,
              totalCount: result?.totalCount,
            };
            state.hasMore = result?.pageIndex * result?.pageSize < result?.totalCount;
          });
        }
      } catch (error) {
        console.log(error);
      } finally {
        Taro.hideLoading();
        set((state) => {
          state.isDataLoaded = false;
        });
      }
    },

    /**
     * 上拉加载
     * @param pageParams 分页
     */
    handlePullUpOrDown: async (pageParams: PageParams, type: string, isAppend = true) => {
      const newPageInfo = { ...pageParams };
      await get().getMyPublishList(newPageInfo, type, isAppend);
    },

    /**
     * 上架/下架需求
     */
    handleReOperate: async (demandId: string, operateType: 'UP' | 'DOWN') => {
      const result = await takeOffShelves({ demandId });
      if (result.success) {
        set((state) => {
          const item = state.myPublishList.find((d) => d.id === demandId);
          if (item) {
            // 1-正常，-1下架
            item.status = operateType === 'UP' ? 1 : -1;
          }
        });
      }
    },

    /**
     * 删除需求
     */
    handleDelete: async (id: string) => {
      const result = await deleteDemand({ id });
      if (result.success) {
        set((state) => {
          state.myPublishList = state.myPublishList.filter((d) => d.id !== id);
        });
      }
    },
  })),
);
